--
-- Author: cm_wang
-- Date: 2017-09-19 10:41:57
--
local DataProxyBase = class("DataProxyBase")

function DataProxyBase:ctor()
	local event = require("framework.common.event").new()
    event:bind(self)
end

function DataProxyBase:onDestroy()
    self:removeAllEventListeners()
end

--设置代理，实现类似KVO观察的模式
function DataProxyBase:setProxy(sourceTable,path)
    local proxy = {}

    local mt =  {
        __newindex = function(t, name, value)
            if sourceTable[name] ~= value then
                local newVal = value
                local oldVal = sourceTable[name]
                if type(value) == "table" then
                    newVal = self:setProxy(value, path .. "." .. name)
                end
               
                sourceTable[name] = newVal

                if oldVal == nil and newVal ~= nil then
                    self:sendDataAddEvent(path,name,newVal)
                elseif oldVal ~= nil and newVal == nil then
                    self:sendDataDelEvent(path,name)
                end
                self:sendDataChangeEvent(path .. "." .. name)
            end
        end,
        __index = function(t, name)
            return sourceTable[name]
        end,
        __next = function(t, k) 
            return next(sourceTable, k)
        end,
        __pairs = function( t )
        	return pairs(sourceTable)
        end,
        __len = function( t )
            return #sourceTable
        end
    }

    for k,v in pairs(sourceTable) do
        if type(v) "table" then
            v = self:setProxy(v,path .. "." .. k)
            sourceTable[k] = v
        end
    end

    setmetatable(proxy, mt)

    return proxy
end

function DataProxyBase:sendDataChangeEvent( key )
	self:dispatchEvent({name=key})
end

function DataProxyBase:sendDataAddEvent(path,key,value)
    self:dispatchEvent({name = "Add_" .. path,key = key,value = value})
end

function DataProxyBase:sendDataDelEvent(path,key)
    self:dispatchEvent({name = "Del_" .. path,key = key})
end

--注册基本属性的键-值观察
--注册后，当对应key路径的用户数据发生变化的时候，会自动调用obfunc
--需要手动移除
function DataProxyBase:addObserver(key, obfunc,tag,priority)
    local target, handler = self:addEventListener(key, obfunc,tag,priority)
	return handler
end

function DataProxyBase:removeObserver(handler)
	return self:removeEventListener(handler)
end



return DataProxyBase